//
//  MineHeaderView.swift
//  MT
//
//  Created by M on 2020/1/5.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import RxSwift
import RxDataSources
import Moya
import Result

@objc
protocol MineHeaderViewDelegate: NSObjectProtocol {
    /// Push To 交易记录控制器
    @objc optional func mineHeaderViewShouldPushToPurchaseRecordController(_ headerView: MineHeaderView)
    
    /// Push To 交易记录控制器
    @objc optional func mineHeaderViewShouldPushToPhotoCollectionController(_ headerView: MineHeaderView)
    
    /// 点击兑换钻石按钮
    @objc optional func mineHeaderViewDidClickExchangeDiamondButton(_ headerView: MineHeaderView)
    
    /// 点击提现按钮
    @objc optional func mineHeaderViewDidClickWithdrawButton(_ headerView: MineHeaderView)
    
    /// 点击充值按钮
    @objc optional func mineHeaderViewDidClickRechargeDiamondButton(_ headerView: MineHeaderView)
    
    /// 点击我的账户按钮
    @objc optional func mineHeaderViewDidClickAmountButton(_ headerView: MineHeaderView)
    
    /// 点击我的礼物按钮
    @objc optional func mineHeaderViewDidClickGiftButton(_ headerView: MineHeaderView)
    /// 点击我的加好友按钮
    @objc optional func mineHeaderViewDidClickAddFriendButton(_ headerView: MineHeaderView)
}

class MineHeaderView: UIView {
    
    /// 代理
    weak var delegate: MineHeaderViewDelegate?

    /// 信息模型
    var model: MineInfoModel? {
        didSet {
            guard let model = model else { return }
            
            /// 头像
//            if let avatar = model.headerUrl {
//                avatarImageView.kf.setImage(with: URL(string: avatar), placeholder: UIImage(named: defaultPlaceholderIcon60x60))
//            }
            
            avatarImageView.mtSetImage(model.headerUrl, nil)
            
            /// 性别
            sexImageView.image = UIImage(named: model.sex == 0 ? "icon_male_small" : "icon_female_small")
            /// 昵称
            nicknameLabel.text = model.nickname
            ///ID
            userIdLabel.text = "觅颜ID:\(model.id ?? 0)"
            
            //等级
            levelLabel.text = "M\(model.levelId)"
            
            amountLab.text = "\(model.ticketAmount)"
            
            giftLab.text = "\(model.giftPrice)"
            
            likeLab.attributedText = mc_add(text: "\(model.likeCount)", UIColor.text.x1d1a1a, font: PingFangSCSemiboldFont(12), appendText: "获赞", UIColor.text.x9b9b9b, appendFont: PingFangSCMediumFont(12))
            //"\(model.likeCount)获赞"
            
            friendsLab.attributedText = mc_add(text: "\(model.friendsCount)", UIColor.text.x1d1a1a, font: PingFangSCSemiboldFont(12), appendText: "好友", UIColor.text.x9b9b9b, appendFont: PingFangSCMediumFont(12))
            //"\(model.friendsCount)好友"
            
            /// 用户信息
            if model.age != nil && model.area != nil {
                userinfoLabel.text = "\(model.age ?? 0)岁 | \(model.area ?? "")"
            } else if model.area == nil {
                userinfoLabel.text = "\(model.age ?? 0)岁"
            } else {
                userinfoLabel.text = "\(model.area ?? "")"
            }
            heightLab.attributedText = mc_add(text: "身高: ", UIColor.text.x9b9b9b, font: PingFangSCRegularFont(12), appendText: model.height != nil ? "\(model.height!)cm" : "-", UIColor.text.x1d1a1a, appendFont: PingFangSCMediumFont(12))
                //mc_addForegroundColor(text: model.height != nil ? "身高:\(model.height!)cm" : "身高:-", UIColor.text.x1d1a1a, range: NSRange.init(location: 3, length: 5))
            weightLab.attributedText = mc_add(text: "体重: ", UIColor.text.x9b9b9b, font: PingFangSCRegularFont(12), appendText: model.weight != nil ? "\(model.weight!)kg" : "-", UIColor.text.x1d1a1a, appendFont: PingFangSCMediumFont(12))
                //mc_addForegroundColor(text: model.weight != nil ? "体重:\(model.weight!)kg" : "体重:-", UIColor.text.x1d1a1a, range: NSRange.init(location: 3, length: 4))
            starLab.attributedText = mc_add(text: "星座: ", UIColor.text.x9b9b9b, font: PingFangSCRegularFont(12), appendText: model.constellation != nil ? "\(model.constellation!)" : "-", UIColor.text.x1d1a1a, appendFont: PingFangSCMediumFont(12))
                //mc_addForegroundColor(text: model.constellation != nil ? "星座:\(model.constellation!)" : "星座:-", UIColor.text.x1d1a1a, range: NSRange.init(location: 3, length: 3))
            jobLab.attributedText = mc_add(text: "职业: ", UIColor.text.x9b9b9b, font: PingFangSCRegularFont(12), appendText: model.position != nil ? "\(model.position!)" : "-", UIColor.text.x1d1a1a, appendFont: PingFangSCMediumFont(12))
                //mc_addForegroundColor(text: model.position != nil ? "职业:\(model.position!)" : "职业:-", UIColor.text.x1d1a1a, range: NSRange.init(location: 3, length: model.position?.length ?? 2))
            degreeLab.attributedText = mc_add(text: "学历: ", UIColor.text.x9b9b9b, font: PingFangSCRegularFont(12), appendText: model.degree != nil ? "\(model.degree!)" : "-", UIColor.text.x1d1a1a, appendFont: PingFangSCMediumFont(12))
                //mc_addForegroundColor(text: model.degree != nil ? "学历:\(model.degree!)" : "学历:-", UIColor.text.x1d1a1a, range: NSRange.init(location: 3, length: model.degree?.length ?? 2))
            signLab.attributedText = mc_add(text: "签名: ", UIColor.text.x9b9b9b, font: PingFangSCRegularFont(12), appendText: model.signature != nil ? "\(model.signature!)" : "-", UIColor.text.x1d1a1a, appendFont: PingFangSCMediumFont(12))
                //mc_addForegroundColor(text: model.signature != nil ? "签名:\(model.signature!)" : "签名:-", UIColor.text.x1d1a1a, range: NSRange.init(location: 3, length: model.signature?.length ?? 2))

            ticketView.balanceLabel.text = "\(model.ticketAmount)"
            diamondView.balanceLabel.text = "\(model.money)"
            if model.certificationType == 0 {
                cerTypeIcon.isHidden = true
                cerButton.isHidden = false
                cerStatusButton.isHidden = true
            } else {
                cerTypeIcon.isHidden = false
                cerButton.isHidden = true
                cerStatusButton.isHidden = false
                /// ooops 2020年06月24日22:40:27 非通过状态下, 不显示 v 标签
                if model.certificationStatus != -1 && model.certificationStatus != 0 {
                    cerTypeIcon.image = UIImage(named: model.certificationType == 1 ? "mine-cer" : "mine-company")
                }
                cerStatusButton.setTitle(cerStatus(status: model.certificationStatus), for: .normal)
            }
            collectionView.reloadData()
            
            /// 判断是否显示加好友按钮
            /// 是否已经是好友关系
            if let username = model.userName {
                JMSGUser.userInfoArray(withUsernameArray: [username]) { (result, error) in
                    if error == nil {
                        let users = result as! [JMSGUser]
                        if let user = users.first, user.isFriend {
                            self.addFriendButton.isHidden = true
                        } else {
                            self.addFriendButton.isHidden = false
                        }
                    } else {
                        self.addFriendButton.isHidden = false
                    }
                }
                /// 如果是自己, 隐藏添加好友按钮
                if username == JMSGUser.myInfo().username {
                    self.addFriendButton.isHidden = true
                }
            } else {
                self.addFriendButton.isHidden = false
            }
        }
    }

    /// 背景图
    lazy var blackImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = UIImage(named: "head-bg")
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    
    /// 用户图标
    lazy var avatarImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        imgView.layer.cornerRadius = 40
        imgView.clipsToBounds = true
        return imgView
    }()
    
    /// 性别图标
    lazy var sexImageView: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        return imgView
    }()
    
    /// 用户名 Label
    lazy var nicknameLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCSemiboldFont(16)
        label.textColor = .white
        label.textAlignment = .left
        return label
    }()
    
    /// 等级 Label
    lazy var levelLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCSemiboldFont(10)
        label.backgroundColor = UIColor.theme.main
        label.textColor = .white
        label.textAlignment = .center
        label.layer.cornerRadius = 6
        label.clipsToBounds = true
        return label
    }()
    
    /// 用户ID
    lazy var userIdLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCSemiboldFont(10)
        label.textColor = .white
        return label
    }()
    
    ///规则
    lazy var ruleBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("等级规则", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(10)
        btn.addTarget(self, action: #selector(headerView(didClickRuleButton:)), for: .touchUpInside)
        btn.adjustsImageWhenHighlighted = false
        return btn
    }()
    
    ///设置按钮
    lazy var settingBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "icon_setting"), for: .normal)
        btn.addTarget(self, action: #selector(headerView(didClickSettingButton:)), for: .touchUpInside)
        btn.adjustsImageWhenHighlighted = false
        return btn
    }()
    
    ///编辑按钮
    lazy var editBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "icon_profile"), for: .normal)
        btn.addTarget(self, action: #selector(headerView(didClickEditButton:)), for: .touchUpInside)
        btn.adjustsImageWhenHighlighted = false
        return btn
    }()
    
    /// 用户信息 Label
    lazy var userinfoLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCMediumFont(12)
        label.textColor = UIColor(hex:0x1d1a1a)
        label.textAlignment = .left
        return label
    }()
    
    /// 邀请好友按钮
    lazy var inviteButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "Invitation"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickAddFriendButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 认证按钮
    lazy var cerButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "Addcertification"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickAddCerButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 我的账户icon
    lazy var amountIcon: UIImageView = {
        let image = UIImageView()
        image.image = UIImage(named: "dimond")
        return image
    }()
    
    /// 我的账户
    lazy var amountLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex:0x1d1a1a)
        label.font = PingFangSCSemiboldFont(14)
        return label
    }()
    
    /// 我的礼物icon
    lazy var giftIcon: UIImageView = {
        let image = UIImageView()
        image.image = UIImage(named: "present")
        return image
    }()
    
    /// 我的礼物
    lazy var giftLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hex:0x1d1a1a)
        label.font = PingFangSCSemiboldFont(14)
        return label
    }()
    
    /// 充值
    lazy var topupButton: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        btn.setTitle("充值", for: .normal)
        btn.layer.cornerRadius = 12
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.backgroundColor = UIColor.theme.main
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickRechargeDiamondButton:)), for: .touchUpInside)
        return btn
    }()
    
    ///获赞数
    lazy var likeLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x1d1a1a
        label.font = PingFangSCSemiboldFont(12)
        label.textAlignment = .right
        return label
    }()
    
    ///好友数
    lazy var friendsLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x1d1a1a
        label.font = PingFangSCSemiboldFont(12)
        label.textAlignment = .right
        return label
    }()
    
    ///身高
    lazy var heightLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCRegularFont(12)
        
        return label
    }()
    
    ///体重
    lazy var weightLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCRegularFont(12)
        return label
    }()
    
    ///星座
    lazy var starLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCRegularFont(12)
        return label
    }()
    
    ///职业
    lazy var jobLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCRegularFont(12)
        return label
    }()
    
    ///学历
    lazy var degreeLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCRegularFont(12)
        return label
    }()
    
    ///签名
    lazy var signLab: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCRegularFont(12)
        return label
    }()
    
    /// 完整信息
    lazy var moreButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "open"), for: .normal)
        btn.setTitle("完整信息", for: .normal)
        btn.setTitleColor(UIColor(hex:0x426bf2), for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(10)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickMoreButton:)), for: .touchUpInside)
        btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
        btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0)
        return btn
    }()
    
    /// 送礼物按钮
    lazy var addFriendButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("+加好友", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = 16
        btn.clipsToBounds = true
        btn.isHidden = true
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.backgroundColor = UIColor(hex:0xff003d)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickSendAddFriendButton:)), for: .touchUpInside)
        return btn
    }()
    
    
    /// 举报按钮
//    lazy var reportButton: UIButton = {
//        let btn = UIButton()
//        btn.setImage(UIImage(named: "more-white"), for: .normal)
//        btn.adjustsImageWhenHighlighted = false
//        btn.addTarget(self, action: #selector(headerView(didClickReportButtonButton:)), for: .touchUpInside)
//        return btn
//    }()
    
    /// 邀请好友按钮
    lazy var sendGiftButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "icon_sendGift"), for: .normal)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickSendGiftButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 加好友按钮
    lazy var addButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("+加好友", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.backgroundColor = UIColor(hex:0xff003d)
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickSendGiftButton:)), for: .touchUpInside)
        return btn
    }()
    
    /// 用户签名 Label
    lazy var signatureLabel: UILabel = {
        let label = UILabel()
        label.text = "个性签名：这个人太忙，还没来得及写签名…"
        label.font = PingFangSCMediumFont(12)
        label.textColor = .white
        label.textAlignment = .left
        return label
    }()
    
    /// 相册
    lazy var collectionView: UICollectionView = {
        let leftRightInset: CGFloat = 18.0
        let spacing: CGFloat = 10.0
        let count: CGFloat = 5.0
        let wh = (ScreenWidth - (leftRightInset * 2) - (spacing * (count - 1))) / count
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: wh, height: wh)
        flowLayout.minimumLineSpacing = spacing
        flowLayout.minimumInteritemSpacing = spacing
        flowLayout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 90), collectionViewLayout: flowLayout)
        cv.delegate = self
        cv.dataSource = self
        cv.backgroundColor = UIColor.common.x161616
        cv.contentInset = UIEdgeInsets(top: 8, left: leftRightInset, bottom: 7, right: leftRightInset)
        cv.showsHorizontalScrollIndicator = false
        cv.showsVerticalScrollIndicator = false
        cv.register(MinePhotoCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: MinePhotoCollectionViewCell.self))
        return cv
    }()
    
    /// 点券 View
    lazy var ticketView: MineBalanceView = {
        let bv = MineBalanceView()
        bv.titleLabel.text = "总点券"
        bv.balanceLabel.text = "0"
        let b1 = button(withTitle: "兑钻石")
        b1.addTarget(self, action: #selector(headerView(didClickExchangeDiamondButton:)), for: .touchUpInside)
        bv.addSubview(b1)
        b1.snp.makeConstraints { (make) in
            make.left.equalTo(bv).offset(17)
            make.bottom.equalTo(bv).offset(-17)
            make.width.equalTo(60)
            make.height.equalTo(20)
        }
        if UserCenter.default.sex == 1 {        
            let b2 = button(withTitle: "提现")
            b2.addTarget(self, action: #selector(headerView(didClickWithdrawButton:)), for: .touchUpInside)
            bv.addSubview(b2)
            b2.snp.makeConstraints { (make) in
                make.right.equalTo(bv).offset(-17)
                make.bottom.width.height.equalTo(b1)
            }
        }
        return bv
    }()
    
    /// 钻石 view
    lazy var diamondView: MineBalanceView = {
        let bv = MineBalanceView()
        bv.titleLabel.text = "总钻石"
        bv.balanceLabel.text = "0"
        let b1 = button(withTitle: "充值")
        b1.addTarget(self, action: #selector(headerView(didClickRechargeDiamondButton:)), for: .touchUpInside)
        bv.addSubview(b1)
        b1.snp.makeConstraints { (make) in
            make.left.equalTo(bv).offset(17)
            make.bottom.equalTo(bv).offset(-17)
            make.width.equalTo(50)
            make.height.equalTo(20)
        }
        return bv
    }()
    
    /// 认证类型
    lazy var cerTypeIcon: UIImageView = {
        let imgView = UIImageView()
        imgView.contentMode = .scaleAspectFill
        imgView.layer.cornerRadius = 12
        imgView.clipsToBounds = true
        return imgView
    }()
    
    /// 认证状态
    lazy var cerStatusButton: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(12)
        btn.layer.cornerRadius = 12
        btn.layer.borderWidth = 1
        btn.layer.borderColor = UIColor.theme.main.cgColor
        btn.adjustsImageWhenHighlighted = false
        btn.addTarget(self, action: #selector(headerView(didClickAddCerButton:)), for: .touchUpInside)
        return btn
    }()
    
    
    private lazy var authProvider: MTProvider<DDCAuthAPI> = {
        let provider = MTProvider<DDCAuthAPI>()
        return provider
    }()
    
    /// MTProvider
    private lazy var provider: MTProvider<HomeApi> = {
        return MTProvider<HomeApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    /// 是否自己
    var isSelf: Bool
    init(frame: CGRect, isSelf: Bool) {
        self.isSelf = isSelf
        super.init(frame: frame)
        initializeUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension MineHeaderView {
    
    private func initializeUI() {
        backgroundColor = UIColor(hex:0xf6f6f6)
        
        addSubview(blackImageView)
        addSubview(avatarImageView)
        addSubview(nicknameLabel)
        addSubview(levelLabel)
        addSubview(userIdLabel)
        

        blackImageView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(self)
            make.height.equalTo(120)
        }
        
        avatarImageView.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(10)
            make.top.equalTo(self).offset(74)
            make.width.height.equalTo(80)
        }
        
        nicknameLabel.snp.makeConstraints { (make) in
            make.left.equalTo(avatarImageView.snp.right).offset(10)
            make.top.equalTo(avatarImageView).offset(1)
            
        }
        
        levelLabel.snp.makeConstraints { (make) in
            make.left.equalTo(nicknameLabel.snp.right).offset(4)
            make.centerY.equalTo(nicknameLabel)
            make.width.equalTo(28)
            make.height.equalTo(12)
            
        }
        
        userIdLabel.snp.makeConstraints { (make) in
            make.top.equalTo(nicknameLabel.snp.bottom).offset(2)
            make.left.equalTo(nicknameLabel)
        }
        
        if isSelf {
            let accountInfo: UIView = accountInfoView()
            let personal: UIView = personalInfoView(isSelf: isSelf)
            let amountImageV = UIImageView()
            amountImageV.image = UIImage(named: "icon_arrow_right_gary")
            
            addSubview(ruleBtn)
            addSubview(amountImageV)
            addSubview(settingBtn)
            addSubview(editBtn)
            addSubview(userinfoLabel)
            addSubview(inviteButton)
            addSubview(accountInfo)
            addSubview(personal)
            addSubview(sendGiftButton)
            addSubview(cerButton)
            addSubview(cerTypeIcon)
            addSubview(cerStatusButton)
            ruleBtn.snp.makeConstraints { (make) in
                make.left.equalTo(levelLabel.snp.right).offset(4)
                make.centerY.equalTo(nicknameLabel)
                make.width.equalTo(50)
                make.height.equalTo(10)
                
            }
            
            amountImageV.snp.makeConstraints { (make) in
                make.centerY.equalTo(ruleBtn)
                make.left.equalTo(ruleBtn.snp.right).offset(-3)
                make.size.equalTo(CGSize(width: 10, height: 10))
            }
            
            settingBtn.snp.makeConstraints { (make) in
                make.top.equalTo(StatusBarHeight)
                make.right.equalTo(-10)
                make.width.right.equalTo(24)
            }
            
            editBtn.snp.makeConstraints { (make) in
                make.top.equalTo(settingBtn)
                make.right.equalTo(settingBtn.snp.left).offset(-10)
                make.width.right.equalTo(24)
            }
            
            userinfoLabel.snp.makeConstraints { (make) in
                make.left.equalTo(nicknameLabel)
                make.top.equalTo(userIdLabel.snp.bottom).offset(15)
            }
            
            cerButton.snp.makeConstraints { (make) in
                make.right.equalTo(-12)
                make.bottom.equalTo(blackImageView).offset(-10)
                make.width.equalTo(80)
                make.height.equalTo(26)
            }
            
            cerStatusButton.snp.makeConstraints { (make) in
                make.right.equalTo(-12)
                make.bottom.equalTo(blackImageView).offset(-10)
                make.width.equalTo(80)
                make.height.equalTo(24)
            }
            
            cerTypeIcon.snp.makeConstraints { (make) in
                make.width.height.equalTo(25)
                make.bottom.equalTo(avatarImageView)
                make.right.equalTo(avatarImageView)
            }
            
            inviteButton.snp.makeConstraints { (make) in
                make.right.equalTo(-12)
                make.top.equalTo(userinfoLabel).offset(-3)
                make.width.equalTo(80)
                make.height.equalTo(26)
            }
            
            accountInfo.snp.makeConstraints { (make) in
                make.top.equalTo(avatarImageView.snp.bottom).offset(10)
                make.left.equalTo(10)
                make.right.equalTo(-10)
                make.height.equalTo(72)
            }
            
            personal.snp.makeConstraints { (make) in
                make.top.equalTo(accountInfo.snp.bottom).offset(15)
                //make.left.equalTo(10)
                //make.right.equalTo(-10)
                make.left.right.equalToSuperview()
                make.height.equalTo(240)
            }
        } else {
            let personal: UIView = personalInfoView(isSelf: isSelf)
            addSubview(addFriendButton)
//            addSubview(reportButton)
            addSubview(personal)
            addSubview(userinfoLabel)
//            reportButton.snp.makeConstraints { (make) in
//                make.top.equalTo(35)
//                make.right.equalTo(-10)
//                make.width.right.equalTo(24)
//            }
            
            addFriendButton.snp.makeConstraints { (make) in
                make.width.equalTo(77)
                make.height.equalTo(32)
                make.right.equalTo(-10)
                make.bottom.equalTo(blackImageView).offset(-8)
            }
            
            userinfoLabel.snp.makeConstraints { (make) in
                make.left.equalTo(nicknameLabel)
                make.top.equalTo(userIdLabel.snp.bottom).offset(10)
            }
            
            personal.snp.makeConstraints { (make) in
                make.top.equalTo(avatarImageView.snp.bottom).offset(15)
                make.left.equalTo(10)
                make.right.equalTo(-10)
                make.height.equalTo(240)
            }
        }
    }
    
    private func accountInfoView() -> UIView {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 16
        
        let amountImageV = UIImageView()
        amountImageV.image = UIImage(named: "icon_arrow_right_gary")
        
        let amountLabTitle = UILabel()
        amountLabTitle.text = "我的账户"
        amountLabTitle.textColor = UIColor(hex:0x1d1a1a)
        amountLabTitle.isUserInteractionEnabled = true
        amountLabTitle.font = PingFangSCMediumFont(12)
        
        let amountLabBtn = UIButton()
        amountLabBtn.adjustsImageWhenHighlighted = false
        amountLabBtn.addTarget(self, action: #selector(headerView(didClickAmountGestureRecognizer:)), for: .touchUpInside)
        
        let giftImageV = UIImageView()
        giftImageV.image = UIImage(named: "icon_arrow_right_gary")
        
        let giftLabTitle = UILabel()
        giftLabTitle.text = "我的礼物"
        giftLabTitle.textColor = UIColor(hex:0x1d1a1a)
        giftLabTitle.font = PingFangSCMediumFont(12)
        giftLabTitle.isUserInteractionEnabled = true
        
        let giftLabBtn = UIButton()
        giftLabBtn.adjustsImageWhenHighlighted = false
        giftLabBtn.addTarget(self, action: #selector(headerView(didClickGiftGestureRecognizer:)), for: .touchUpInside)
        
        let lineview = UIView()
        lineview.backgroundColor = UIColor(hex:0xe6e6e6)
        
        view.addSubview(amountLabTitle)
        view.addSubview(giftLabTitle)
        view.addSubview(amountLab)
        view.addSubview(amountIcon)
        view.addSubview(amountLabBtn)
        view.addSubview(lineview)
        view.addSubview(giftLab)
        view.addSubview(giftIcon)
        view.addSubview(giftLabBtn)
        view.addSubview(topupButton)
        
        view.addSubview(amountImageV)
        view.addSubview(giftImageV)
        
        amountLabTitle.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.top.equalTo(view).offset(14)
        }
        
        amountIcon.snp.makeConstraints { (make) in
            make.left.equalTo(amountLabTitle)
            make.top.equalTo(amountLabTitle.snp.bottom).offset(7)
            make.width.height.equalTo(24)
        }
        
        amountLab.snp.makeConstraints { (make) in
            make.centerY.equalTo(amountIcon)
            make.left.equalTo(amountIcon.snp.right).offset(4)
        }
        
        
        amountImageV.snp.makeConstraints { (make) in
            make.left.equalTo(amountLabTitle.snp.right)
            make.centerY.equalTo(amountLabTitle)
            make.size.equalTo(CGSize(width: 15, height: 15))
        }
        
        amountLabBtn.snp.makeConstraints { (make) in
            make.left.top.equalTo(amountLabTitle)
            make.right.equalTo(amountImageV)
            make.bottom.equalTo(amountIcon)
        }
        
        giftImageV.snp.makeConstraints { (make) in
            make.left.equalTo(giftLabTitle.snp.right)
            make.centerY.equalTo(giftLabTitle)
            make.size.equalTo(CGSize(width: 15, height: 15))
        }
        
        lineview.snp.makeConstraints { (make) in
            make.top.equalTo(34)
            make.left.equalTo(view).offset(125)
            make.width.equalTo(1)
            make.height.equalTo(24)
        }
        
        giftLabTitle.snp.makeConstraints { (make) in
            make.left.equalTo(lineview.snp.right).offset(20)
            make.top.equalTo(amountLabTitle)
        }
        
        giftIcon.snp.makeConstraints { (make) in
            make.left.equalTo(giftLabTitle)
            make.top.equalTo(giftLabTitle.snp.bottom).offset(7)
            make.width.height.equalTo(24)
        }
        
        giftLab.snp.makeConstraints { (make) in
            make.centerY.equalTo(giftIcon)
            make.left.equalTo(giftIcon.snp.right).offset(4)
        }
        
        giftLabBtn.snp.makeConstraints { (make) in
            make.left.top.equalTo(giftLabTitle)
            make.right.equalTo(giftImageV)
            make.bottom.equalTo(giftIcon)
        }
        
        topupButton.snp.makeConstraints { (make) in
            make.centerY.equalTo(view)
            make.right.equalTo(view).offset(-10)
            make.width.equalTo(64)
            make.height.equalTo(24)
        }
        return view
    }
    
    private func personalInfoView(isSelf: Bool) -> UIView {
        let view = UIView()
        view.backgroundColor = .clear
        
        let personalLab = UILabel()
        personalLab.text = isSelf ? "个人信息" : "Ta的信息"
        personalLab.textColor = UIColor.text.x1d1a1a
        personalLab.font = PingFangSCSemiboldFont(16)
        
        let lineView = UIView()
        lineView.backgroundColor = UIColor(hex:0xe6e6e6)
        
        let videoLab = UILabel()
        videoLab.text = isSelf ? "我的动态" : "Ta的动态"
        videoLab.textColor = UIColor.text.x1d1a1a
        videoLab.font = PingFangSCSemiboldFont(16)
        
        let lineView2 = UIView()
        lineView2.backgroundColor = UIColor(hex:0xe6e6e6)
        
        view.addSubview(personalLab)
        view.addSubview(likeLab)
        view.addSubview(friendsLab)
        view.addSubview(heightLab)
        view.addSubview(weightLab)
        view.addSubview(starLab)
        view.addSubview(jobLab)
        view.addSubview(degreeLab)
        view.addSubview(signLab)
        view.addSubview(lineView)
        view.addSubview(moreButton)
        view.addSubview(videoLab)
        view.addSubview(lineView2)
        
        personalLab.snp.makeConstraints { (make) in
            make.top.equalTo(20)
            make.left.equalTo(10)
            make.width.equalTo(80)
        }
        
        friendsLab.snp.makeConstraints { (make) in
            make.centerY.equalTo(personalLab)
            make.right.equalTo(view).offset(-10)
        }
        
        likeLab.snp.makeConstraints { (make) in
            make.centerY.equalTo(friendsLab)
            make.right.equalTo(friendsLab.snp.left).offset(-10)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.top.equalTo(personalLab.snp.bottom).offset(8)
            make.height.equalTo(1)
        }

        heightLab.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(10)
            make.top.equalTo(lineView.snp.bottom).offset(20)
        }

        weightLab.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(198)
            make.top.equalTo(heightLab)
        }

        starLab.snp.makeConstraints { (make) in
            make.left.equalTo(heightLab)
            make.top.equalTo(heightLab.snp.bottom).offset(10)
        }

        jobLab.snp.makeConstraints { (make) in
            make.left.equalTo(weightLab)
            make.top.equalTo(starLab)
        }

        degreeLab.snp.makeConstraints { (make) in
            make.left.equalTo(heightLab)
            make.top.equalTo(starLab.snp.bottom).offset(10)
        }

        signLab.snp.makeConstraints { (make) in
            make.left.equalTo(heightLab)
            make.top.equalTo(degreeLab.snp.bottom).offset(10)
        }

        moreButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(view)
            make.top.equalTo(signLab.snp.bottom).offset(13)
            make.width.equalTo(60)
            make.height.equalTo(12)
        }
        
        videoLab.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            //make.top.equalTo(moreButton.snp.bottom).offset(20)
            make.bottom.equalToSuperview().offset(-8)
        }
        
        lineView2.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            //make.top.equalTo(videoLab.snp.bottom).offset(8)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        
        return view
    }
    
    private func button(withTitle title: String) -> UIButton {
        let b = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 20))
        b.adjustsImageWhenHighlighted = false
        b.setTitle(title, for: .normal)
        b.setTitleColor(.white, for: .normal)
        b.titleLabel?.font = PingFangSCRegularFont(14)
        b.setImage(UIImage(named: "icon_arrow_right"), for: .normal)
        if let imageView = b.imageView { b.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageView.frame.width, bottom: 0, right: imageView.frame.width) }
        if let titleLabel = b.titleLabel { b.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleLabel.frame.width + 5, bottom: 0, right: -titleLabel.frame.width) }
        return b
    }
    
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MineHeaderView {
    
    private func headerView(didClickAmountGestureRecognizer gestureRecognizer: UITapGestureRecognizer){
        if let delegate = delegate {
            delegate.mineHeaderViewDidClickAmountButton?(self)
        }
    }
    
    private func headerView(didClickGiftGestureRecognizer gestureRecognizer: UITapGestureRecognizer){
        if let delegate = delegate {
            delegate.mineHeaderViewDidClickGiftButton?(self)
        }
    }
    
//    private func headerView(didClickReportButtonButton sender: UIButton) {
//        let xibView = MTFeedbackAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
//        xibView.delegate = self
//        UIApplication.mt_keyWindow?.rootViewController?.view.addSubview(xibView)
//    }
    
    /// 换钻石
    private func headerView(didClickExchangeDiamondButton sender: UIButton) {
        if let delegate = delegate {
            delegate.mineHeaderViewDidClickExchangeDiamondButton?(self)
        }
    }
    
    /// 提现
    private func headerView(didClickWithdrawButton sender: UIButton) {
        if let delegate = delegate {
            delegate.mineHeaderViewDidClickWithdrawButton?(self)
        }
    }
    
    /// 充值钻石
    private func headerView(didClickRechargeDiamondButton sender: UIButton) {
        if let delegate = delegate {
            delegate.mineHeaderViewDidClickRechargeDiamondButton?(self)
        }
    }
    
    private func headerView(didClickAddFriendButton sender: UIButton) {
//        guard let model = model, let username = model.userName else { return }
        
        let vc = MTInviteController()
        vc.model = model
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
    }
    
    private func headerView(didClickAddCerButton sender: UIButton) {
        //        guard let model = model, let username = model.userName else { return }
        
        let vc = MTAuthenticationController()
        vc.minemodel = model
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
    }
    
    
    private func headerView(didClickSendGiftButton sender: UIButton) {
        guard let model = model, let username = model.userName else { return }
        
        let vc = MTAddFriendViewController()
        vc.userName = username
        vc.nickName = model.nickname
        
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
//        guard let model = model, let username = model.userName else { return }
//
//        NotificationCenter.default.post(name: GlobalNotificationName.homeInteractionSendGift.name, object: nil, userInfo: ["imUserName" : username])
    }
    
    private func headerView(didClickSendAddFriendButton sender: UIButton) {
        self.delegate?.mineHeaderViewDidClickAddFriendButton?(self)
    }
    
    private func headerView(didClickMoreButton sender: UIButton) {
        let vc = MineInfoViewController()
        vc.model = model
        vc.isSelf = isSelf
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
    }
    
    private func headerView(didClickSettingButton sender: UIButton) {
        let vc = MineSettingViewController()
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
    }
    
    private func headerView(didClickEditButton sender: UIButton) {
        let vc = MineProfileController()
        vc.model = model
        let nav: BaseNavController? = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.selectedViewController as? BaseNavController
        nav?.pushViewController(vc, animated: true)
    }
    
    private func headerView(didClickRuleButton sender: UIButton) {
        let xibView = UserLevelRuleAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
        UIApplication.mt_keyWindow?.rootViewController?.view.addSubview(xibView)
    }
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UICollectionViewDelegate ----------------------
extension MineHeaderView: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let delegate = delegate {
            delegate.mineHeaderViewShouldPushToPhotoCollectionController?(self)
        }
    }
    
}

// MARK: ------------------ UICollectionViewDataSource ----------------------
extension MineHeaderView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        guard let imgList = model?.imgList else { return 0 }
        return imgList.count > 5 ? 5 : imgList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MinePhotoCollectionViewCell.self), for: indexPath) as? MinePhotoCollectionViewCell else {
            return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: MinePhotoCollectionViewCell.self), for: indexPath)
        }
        cell.model = self.model?.imgList?[indexPath.item]
        cell.remainCount = indexPath.item == 4 ? ((self.model?.imgList?.count ?? 0) - 5) : 0
        return cell
    }
    
}

// MARK: ------------------------------------ 余额 View ----------------------------------------
class MineBalanceView: UIView {
    
    /// 标题
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCRegularFont(14)
        label.textColor = .white
        label.textAlignment = .left
        return label
    }()
    
    /// 余额
    lazy var balanceLabel: UILabel = {
        let label = UILabel()
        label.font = PingFangSCSemiboldFont(35)
        label.textColor = UIColor.theme.main
        label.textAlignment = .left
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------------------------ 初始化 ----------------------------------------
extension MineBalanceView {
    
    private func initializeUI() {
        backgroundColor = .black
        layer.cornerRadius = 10
        layer.borderWidth = 1
        layer.borderColor = UIColor.theme.main.cgColor
        
        addSubview(titleLabel)
        addSubview(balanceLabel)
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.left.equalTo(self).offset(16)
        }
        
        balanceLabel.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(5)
            make.left.equalTo(titleLabel)
        }
    }
    
}

extension MineHeaderView: MTFeedbackAlertViewDelegate {
    func reportClick() {
        if let un = self.model?.userName {
            MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "正在上报, 请稍后")
            authProvider.originRequest(.report(username: un), callbackQueue: .main, progress: nil) { [weak self] (result, _) in
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "感谢您的反馈, 系统将在24小时内处理")
                    } else {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "举报失败, 请稍后重试")
                    }
                    DispatchQueue.main.after(2) {
                        MBProgressHUD_JChat.dismiss(UIApplication.mt_keyWindow)
                    }
                    break
                case .failure(_):
                    MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "举报失败, 请稍后重试")
                    DispatchQueue.main.after(1) {

                        DispatchQueue.main.after(2) {
                            MBProgressHUD_JChat.dismiss(UIApplication.mt_keyWindow)
                        }
                    }
                    break
                }

            }
        }
    }
    
    func blackClick() {
        if let id = self.model?.id {
            provider.rx.requestResult(.moment(blackUserId: id )).subscribe(onNext: { (result: Result<MineInfoListResponseModel, AnyError>, isCache: Bool) in
                switch result {
                case let .success(response):
                    if response.code == 200 {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "处理成功")
                    } else {
                        MBProgressHUD_JChat.showLoading(UIApplication.mt_keyWindow, text: "拉黑失败, 请稍后重试")
                    }
                    break
                    
                case .failure(_):
                    break
                }
            }).disposed(by: disposeBag)
        }
    }
}

extension MineHeaderView {
    /// 设置字体颜色
    public func mc_add(text: String,_ color: UIColor, font: UIFont = PingFangSCSemiboldFont(12), appendText: String = "-", _ appendColor: UIColor, appendFont: UIFont = PingFangSCMediumFont(12)) -> NSMutableAttributedString {
        
        let markAttrs = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font : font]
        let appendAttrs = [NSAttributedString.Key.foregroundColor: appendColor, NSAttributedString.Key.font : appendFont]
        
        let markAttribute = NSMutableAttributedString(string: text, attributes: markAttrs)
        let markAppendAttr = NSAttributedString(string: appendText, attributes: appendAttrs)
        
        markAttribute.append(markAppendAttr)
        
        return markAttribute
    }
    
    /// 设置字体颜色
    public func mc_addForegroundColor(text: String,_ color: UIColor, range: NSRange) -> NSMutableAttributedString {
        let markAttribute = NSMutableAttributedString(string: text)
        let markAttrs = [NSAttributedString.Key.foregroundColor: UIColor.text.x1d1a1a, NSAttributedString.Key.font : PingFangSCSemiboldFont(12)]
        let attrs_t = [NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.font : PingFangSCMediumFont(12)]
        markAttribute.addAttributes(markAttrs, range: NSRange(location: 0, length: text.length - 1))
        markAttribute.addAttributes(attrs_t, range: NSRange(location: text.length - 1, length: text.length))
        
        if markAttribute.length < range.location + range.length {
            return markAttribute
        }
        
        let attrs = [NSAttributedString.Key.foregroundColor: color]
        markAttribute.addAttributes(attrs, range: range)
        return markAttribute
    }
    
    private func cerStatus(status: Int) -> String {
        switch status {
        case -1:
            return "未认证"
        case 0:
            return "审核中"
        case 1:
            return "已通过"
        case 2:
            return "已拒绝"
        default:
            return "未认证"
        }
    }
}

